<?php

namespace App\Console\Commands\Mybank;

use App\Exceptions\BaseException;
use App\Kuafu\Mybank\Model\MybankBillRecordModel;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\WaiMaiShopMappingModel;
use App\Library\FeiShu\SendFs;
use App\Remote\MeiTuan\MeiTuanShopRemote;
use App\Remote\MeiTuan\MeiTuanTakeAwayOrderRemote;
use App\Remote\Tiger\Common\CommonRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;

class SyncMeiTuanTakeAwayOrderDetailCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mybank:SyncMeiTuanTakeAwayOrderDetail';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '分账：同步门店美团外卖订单数据明细';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     */
    public function handle(): int
    {
        if (isTest()){
            return 0;
        }
        $nowDay = formatDateYmd(time());
        logMsg("【 网商 】 【 美团 】 【 同步美团外卖数据 】 【 {$nowDay} 】", ["executeTime" => formatDate(time())], true, true,
            SendFs::ROBOT_BATCH_BILL_MATCH);

        $config = [
            ["module" => "guanyuanDB", "name" => "meituanWaimaiCookie[kfzc2019]"],
            ["module" => "guanyuanDB", "name" => "meituanWaimaiCookie[kfzc2021]"],
            ["module" => "guanyuanDB", "name" => "meituanWaimaiCookie[kfzcsd001]"],
        ];

        foreach ($config as $configRow) {
            try {
                $this->getOutput()->comment("美团账号 【" . $configRow["name"] . "】 数据读取写入");
                $cookie = CommonRemote::getConfigDetail($configRow["module"], $configRow["name"])["value"];

                //todo 获取门店列表
                $pageNum    = 1;
                $pageSize   = 500;
                $runShopIds = [];
                while (true) {
                    MeiTuanShopRemote::$requestTimeOut = 20;
                    $shopRemoteResponse                = MeiTuanShopRemote::shopList($cookie, $pageNum, $pageSize);
                    if ($shopRemoteResponse["dataList"]) {
                        $shopListCollection              = collect($shopRemoteResponse["dataList"]);
                        $thirdShopIdGroup                = $shopListCollection->pluck("id")->toArray();
                        $waiMaiShopMappingListCollection = WaiMaiShopMappingModel::query()
                                                                                 ->where("sourceType",
                                                                                     WaiMaiDBEnum::SOURCE_TYPE_MT_WM)
                                                                                 ->whereIn("thirdShopId",
                                                                                     $thirdShopIdGroup)
                                                                                 ->get();

                        logMsg(
                            "美团外卖门店匹配rms门店数据失败  第【{$pageNum}】页",
                            $shopListCollection->whereNotIn("id",
                                $waiMaiShopMappingListCollection->pluck("thirdShopId")->toArray())
                                               ->map(function ($v) {
                                                   return [
                                                       "id"           => $v["id"],
                                                       "poiName"      => $v["poiName"],
                                                       "businessDesc" => $v["businessDesc"]
                                                   ];
                                               })->values()->toArray(),
                            true,
                            false,
                            SendFs::ROBOT_BATCH_BILL_MATCH
                        );

                        $waiMaiShopMappingListCollection->each(
                            function (WaiMaiShopMappingModel $waiMaiShopMappingModel) use ($cookie, &$runShopIds) {
                                $this->getOutput()
                                     ->info("获取门店 【{$waiMaiShopMappingModel->thirdShopId}】【{$waiMaiShopMappingModel->thirdShopName}】外卖数据");
                                $lastBillRecord = MybankBillRecordModel::query()
                                                                       ->where("shopId",
                                                                           $waiMaiShopMappingModel->shopId)
                                                                       ->where("source",
                                                                           MybankBillRecordModel::SOURCE_MEITUAN)
                                                                       ->orderBy("id", "desc")
                                                                       ->first();

                                $billRecordPageNum  = 1;
                                $billRecordPageSize = 100;
                                if (!in_array($waiMaiShopMappingModel->thirdShopId, $runShopIds)) {
                                    array_push($runShopIds, $waiMaiShopMappingModel->thirdShopId);

                                    $historySettleBillList = MeiTuanTakeAwayOrderRemote::poiAccountFlows(
                                        $cookie,
                                        $waiMaiShopMappingModel->thirdShopId,
                                        $billRecordPageNum,
                                        $billRecordPageSize
                                    );

                                    if ($lastBillRecord) {
                                        $this->getOutput()->info("查询 最后一条账单之后数据 插入");

                                        if (!empty($historySettleBillList["wmAccountFlowListResponseList"])) {
                                            $searchBill = collect($historySettleBillList["wmAccountFlowListResponseList"])
                                                ->where("outId", explode("-", $lastBillRecord->transId)[0]);
                                            if ($searchBill->isNotEmpty()) {
                                                $sliceBill = array_slice($historySettleBillList["wmAccountFlowListResponseList"],
                                                    0, $searchBill->keys()->first());
                                                $this->billInsert($sliceBill, $waiMaiShopMappingModel, $cookie);
                                            } else {
                                                $this->billInsert(
                                                    $historySettleBillList["wmAccountFlowListResponseList"],
                                                    $waiMaiShopMappingModel,
                                                    $cookie
                                                );
                                            }
                                        }
                                    } else {
                                        $this->getOutput()->info("查询 全量数据 插入");

                                        $billRecordPageNum = ceil($historySettleBillList["totalCount"] / $billRecordPageSize);
                                        while ($billRecordPageNum > 0) {
                                            $historySettleBillList = MeiTuanTakeAwayOrderRemote::poiAccountFlows(
                                                $cookie,
                                                $waiMaiShopMappingModel->thirdShopId,
                                                $billRecordPageNum,
                                                $billRecordPageSize
                                            );

                                            if (!empty($historySettleBillList["wmAccountFlowListResponseList"])) {
                                                $this->billInsert(
                                                    $historySettleBillList["wmAccountFlowListResponseList"],
                                                    $waiMaiShopMappingModel,
                                                    $cookie
                                                );

                                                $billRecordPageNum--;
                                            } else {
                                                break;
                                            }
                                        }
                                    }
                                }
                            });
                        $pageNum++;
                    } else {
                        $this->getOutput()->error(vsprintf("总计门店 【%d】 家, 共执行门店 【%d】 家", [
                            $shopRemoteResponse['totalCount'],
                            count($runShopIds)
                        ]));
                        break;
                    }
                }
            } catch (\Exception $exception) {
                logException(
                    "美团账号【{$configRow["name"]}】门店分账明细获取失败",
                    $exception,
                    ["cookieName" => $configRow["name"]],
                    true,
                    true
                );
            }
        }

        return 0;
    }

    /**
     * 账单写入
     *
     * @param array $historySettleBillList
     * @param WaiMaiShopMappingModel $waiMaiShopMappingModel
     * @param string $cookie
     * @throws BaseException
     * @throws GuzzleException
     */
    public function billInsert(
        array $historySettleBillList,
        WaiMaiShopMappingModel $waiMaiShopMappingModel,
        string $cookie
    ) {
        collect($historySettleBillList)->reverse()->each(function ($billRecord) use (
            $waiMaiShopMappingModel,
            $cookie
        ) {
            $getTransTypeFunc = function ($flowType) {
                switch ($flowType) {
                    case 2:
                        return MybankBillRecordModel::WITHDRAW_TRANS_TYPE;
                    case 6:
                        return MybankBillRecordModel::INCOME_TRANS_TYPE;
                }
            };

            $transType = $getTransTypeFunc($billRecord["flowType"]);
            if ($billRecord["flowType"] == 6) {
                $settleBillDetailList = MeiTuanTakeAwayOrderRemote::settleBillDetail(
                    $cookie,
                    $waiMaiShopMappingModel->thirdShopId,
                    $billRecord["outId"]
                );
                $nowMoney             = $billRecord["balanceCent"] - $billRecord["moneyCent"];
                collect($settleBillDetailList["dailyBills"])
                    ->sortBy("dailyBillDateTimestamp")
                    ->each(function ($settleBillDetail, $key) use (
                        $transType,
                        $billRecord,
                        $waiMaiShopMappingModel,
                        &$nowMoney
                    ) {
                        $nowMoney = $nowMoney + $settleBillDetail["dailyBillAmount"];
                        try {
                            MybankBillRecordModel::query()->insert([
                                "shopId"               => $waiMaiShopMappingModel->shopId,
                                "source"               => MybankBillRecordModel::SOURCE_MEITUAN,
                                "transDate"            => strtotime($billRecord["flowTime"]),
                                "transType"            => $transType,
                                "displayTransType"     => MybankBillRecordModel::MAPPING_TRANS_TYPE[$transType],
                                "transId"              => $billRecord["outId"] . "-" . ($key + 1),
                                "transStatus"          => MybankBillRecordModel::TRANS_STATUS_SUC,
                                "transDesc"            => $billRecord["flowTypeName"] . "-" . $billRecord["flowStateName"],
                                "billDate"             => strtotime($settleBillDetail["dailyBillDate"]),
                                "transAmount"          => $settleBillDetail["dailyBillAmount"],
                                "afterRemainingAmount" => $nowMoney,
                                "remark"               => vsprintf("[%s]-[%s]-[%s]-[%s]-[%s]-[%s]", [
                                    $waiMaiShopMappingModel->thirdShopId,
                                    $billRecord["flowTypeName"],
                                    $billRecord["flowStateName"],
                                    $billRecord["flowTime"],
                                    $billRecord["flowTypeComment"],
                                    $settleBillDetail["dailyBillDate"]
                                ]),
                                "createdAt"            => time(),
                                "updatedAt"            => time()
                            ]);
                        } catch (\Exception $exception) {

                        }
                    });
            } else {
                try {
                    MybankBillRecordModel::query()->insert([
                        "shopId"               => $waiMaiShopMappingModel->shopId,
                        "source"               => MybankBillRecordModel::SOURCE_MEITUAN,
                        "transDate"            => strtotime($billRecord["flowTime"]),
                        "transType"            => $transType,
                        "displayTransType"     => MybankBillRecordModel::MAPPING_TRANS_TYPE[$transType],
                        "transId"              => $billRecord["outId"],
                        "transStatus"          => MybankBillRecordModel::TRANS_STATUS_SUC,
                        "transDesc"            => $billRecord["flowTypeName"] . "-" . $billRecord["flowStateName"],
                        "billDate"             => strtotime(formatDateYmd(strtotime($billRecord["flowTime"]))),
                        "transAmount"          => trim($billRecord["moneyCent"],
                            "-"),
                        "afterRemainingAmount" => $billRecord["balanceCent"],
                        "remark"               => vsprintf("[%s]-[%s]-[%s]-[%s]-[%s]", [
                            $waiMaiShopMappingModel->thirdShopId,
                            $billRecord["flowTypeName"],
                            $billRecord["flowStateName"],
                            $billRecord["flowTime"],
                            $billRecord["flowTypeComment"]
                        ]),
                        "createdAt"            => time(),
                        "updatedAt"            => time()
                    ]);
                } catch (\Exception $exception) {

                }
            }
        });
    }
}
